package com.peng.messengerdemo;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Created by Mr.Q on 2017/12/18.
 * 描述:运行在另一个进程的Service
 */

public class MessengerService extends Service {

    private static final String TAG = "MessengerService";
    private Messenger messengerClient;

    public class MessengerHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case Constants.MESSAGE_FROM_CLIENT:
                    Log.d(TAG, "handleMessage: " + msg.getData().getString("msg"));
                    messengerClient = msg.replyTo;
                    Message message = Message.obtain(null,Constants.MESSAGE_FROM_SERVICE);
                    Bundle bundle = new Bundle();
                    bundle.putString("msg","已经收到相关消息");
                    message.setData(bundle);
                    try {
                        messengerClient.send(message);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

    private final Messenger messenger = new Messenger(new MessengerHandler());

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return messenger.getBinder();
    }
}
